<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录人数：{{ total }}</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/employees/import')">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column>
            <template v-slot="{row}">
              <img-holder class="avatar" :src="row.staffPhoto" alt="" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              {{ formatEmployee(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push('employees/detail/'+ row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[5, 10, 20, 25]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增员工弹框 -->
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="hClose"
    >
      <emp-dialog ref="empDialog" @close="showDialog=false" @success="hSuccess" />
    </el-dialog>

    <!-- 角色分配弹窗 -->
    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <assign-role v-if="showDialogRole" :id="cruId" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>
<script>
import { deleteEmployees, getEmployees } from '@/api/employee'
import employeesCode from '@/constant/employees'
import empDialog from './empDialog.vue'
import assignRole from './assignRole.vue'

const obj = {}
employeesCode.hireType.forEach(item => { // 映射成为 {1: '正式', 2: '非正式'}
  obj[item.id] = item.value
})

export default {
  components: { empDialog, assignRole },
  data() {
    return {
      list: [],
      total: 0,
      cruId: '',
      showDialogRole: false,
      showDialog: false,
      q: {
        page: 1,
        size: 5
      }
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 分页函数
    handleSizeChange(size) {
      this.q.size = size
      this.loadEmployees()
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmployees()
    },
    async loadEmployees() {
      const res = await getEmployees(this.q)
      // console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    formatEmployee(id) {
      /* const result = employeesCode.hireType.find(item => item.id === id)
      if (result) {
        return result.value
      } else {
        return '未知'
      } */
      return obj[id]
    },
    async hDel(id) {
      try {
        await this.$confirm('您确定要删除吗？', '提示', { type: 'warning' })
        const res = await deleteEmployees(id)
        // console.log(res)
        this.$message.success(res.message)
        // 判断如果删除到当前页面最后一个使，页面自减
        if (this.list.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.loadEmployees()
      } catch (e) {
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hSuccess() {
      this.showDialog = false
      // 添加后,跳到最后一页显示
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployees()
    },
    // 关闭弹窗后清空表单已经校验结果  通过调用子组件里的方法
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    async hExport() {
      // 请求列表全部数据
      const res = await getEmployees({ page: 1, size: this.total })
      // console.log(res)
      const list = res.data.rows
      const { header, data } = this.formatTran(list)
      const excel = await import('@/vendor/Export2Excel')
      // excel表示导入的模块对象
      // console.log(excel)
      excel.export_json_to_excel({
        header, // 表头 必填
        data, // 具体数据 必填
        filename: '员工名单', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
      })
    },
    formatTran(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      let data = []
      const first = list[0]
      header = Object.keys(first).map(item => mapInfo[item])
      data = list.map(item => {
        const key = item['formOfEmployment']
        item['formOfEmployment'] = obj[key]
        return Object.values(item)
      })
      return { header, data }
    },
    hAssign(id) {
      this.showDialogRole = true
      this.cruId = id
    }
  }
}
</script>
<style lang="scss" scope>
  .el-pagination{
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
</style>
